# encoding:utf8

import logging
from functools import wraps
import pymongo


def chk_collection(method):
    @wraps(method)
    def wrapper(self, *args, **kwargs):
        if self._enable_collection():
            return
        return method(self, *args, **kwargs)

    return wrapper


class DbMgr():
    '''数据库管理类'''
    _conn = None
    _db = None

    _cltname = None

    def __init__(self, host, port):
        logging.info("Init DataBase...")
        try:
            if self._conn is None:
                self._conn = pymongo.MongoClient(host=host, port=port)
                logging.info("DB _conn to HOST %s:%s success!",
                             str(host), str(port))
            else:
                logging.info("DB _conn inited!")
        except:
            logging.error("DB _conn failed!")

    def __isenable(self):
        if self._db is None:
            return True

    def _enable_collection(self):
        if not self._cltname:
            logging.error("No collection choosed!")
            return True

    def usedb(self, dbname, username=None, pwd=None):
        '''切换、使用数据库'''
        logging.info("DB use db--> %s", dbname)
        self._db = self._conn[dbname]
        if (username and pwd):
            self._db.authenticate(username, pwd)

    def use_collection(self, collectionname):
        '''切换、使用表单'''
        logging.info("DB use collection--> %s", collectionname)
        olddb = self._db
        self._db = olddb[collectionname]
        self._cltname = collectionname
        return self._db

    @chk_collection
    def insert(self, doc):
        '''塞入数据'''
        self._db.insert(doc)

    @chk_collection
    def find_one(self, resuledoc):
        '''查看单条'''
        try:
            ret = self._db.find_one(resuledoc)
            return ret
        except:
            logging.error("DB find failed")

    @chk_collection
    def remove(self, resuledoc):
        '''删除单条'''
        self._db.remove(resuledoc)

    @chk_collection
    def get_course(self):
        '''获得游标'''
        return self._db.find()

    @chk_collection
    def db(self):
        '''当前数据库'''
        return self._db

    @chk_collection
    def update(self, finddic, setdic):
        '''更新数据库'''
        self._db.update(finddic, setdic)

    def close(self):
        '''关闭链接'''
        self._conn.close()
